import {Component, OnInit, Input, ViewChild, ElementRef} from '@angular/core';
import {
  FormBuilder, FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import {NzModalSubject, NzMessageService} from 'ng-zorro-antd';
import {UMeditorComponent} from 'ngx-umeditor'
import {QuestionListService} from '../list.service';
@Component({
  selector: 'app-question-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.less'],
  providers: [QuestionListService]
})
export class QuestionEditComponent implements OnInit {
  validateForm: FormGroup;
  _questionModel: any;
  kindList: any[];
  levelList: any[];
  typeList: any[];
  full_source: any;
  answerList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  chooseAnswer: any[] = [];
  showStatus: boolean = true;

  config: any = {
    toolbar: ['undo redo | bold italic underline'],
    initialFrameHeight: 100
  };
  /**
   * 表单模型对象
   * @type {{name: string; nickName: string; gender: string; age: string; phone: string; email: string; address: string}}
   */
  formData = {
    id:'',
    description: '',
    options: [] = [],
    answer: [],
    score: '',
    type: null,
    kind: '',
    level: ''
  };

  @Input()
  set questionModel(value: any) {
    this._questionModel = value;
  }
  @Input()
  set kind(value: any[]) {
    this.kindList = value;
  }
  @Input()
  set level(value: any[]) {
    this.levelList = value;
  }
  @Input()
  set type(value: any[]) {
    this.typeList = value;
  }
  @ViewChild('full') full: UMeditorComponent;

  constructor(private questionListService: QuestionListService, private el: ElementRef, private message: NzMessageService, private fb: FormBuilder, private subject: NzModalSubject) {
    console.log('constructor');
    this.subject.on('onDestory', () => {
      console.log('destroy');
    });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      kind: [null, [Validators.required]],
      type: [null, [Validators.required]],
      level: [null, [Validators.required]],
      description: [null, [Validators.required]],
      answer: [null, [Validators.required]],
      score: [null, [Validators.required]]
    });
    if (this._questionModel) {
      this.formData.id = this._questionModel.qid;
      this.formData.type = this._questionModel.type;
      this.formData.description = this._questionModel.description;
      this.formData.answer = this._questionModel.answer;
      this.formData.score = this._questionModel.score;
      this.formData.level = this._questionModel.level;
      this._questionModel.options;
      console.log(this._questionModel.options);
      const self = this;
      this._questionModel.options.forEach(function (value, index) {
        self.addField(null, value.value);
      })

    }
  }

  getAllHtml() {
    // 通过 `this.full.Instance` 访问umeditor实例对象
    alert(this.full.Instance.getAllHtml())
  }

  initFormGroup(type:number) {
    if (type === 0 || type === 1) {

      this.addField();
      this.showStatus = true;
    } else {
      this.formData.options = [];
      this.showStatus = false;
    }
  }

  /**
   * 表单提交方法
   * @private
   */
  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    // data submit
    console.log(this.formData);
    if (this.formData.id) {
      console.log('update');
      this.questionListService.update(this.formData.id, this.formData).then(()=> this.subject.destroy('onOk'));
    } else {
      console.log('add');
      this.questionListService.create(this.formData).then(()=> this.subject.destroy('onOk'));
    }
  }

  _cancel() {
    this.subject.destroy('onCancel');
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  addField(e?: MouseEvent, value? : string) {
    if (e) {
      e.preventDefault();
    }
    const key = (this.formData.options.length > 0) ? this.answerList[this.formData.options.length] : this.answerList[0];
    const control = {
      key:key,
      value: value? value : ''
    };
    const index = this.formData.options.push(control);
    this.validateForm.addControl(this.formData.options[index - 1].value, new FormControl(null, Validators.required));
    this.createChooseAnswerList();
  }

  removeField(i, e: MouseEvent) {
    e.preventDefault();
    if (this.formData.options.length > 1) {
      const index = this.formData.options.indexOf(i);
      this.formData.options.splice(index, 1);
      this.validateForm.removeControl(i.value);
      this.formData.answer = [];
      this.createChooseAnswerList();
    }
  }

  questionTypeChange(event) {
    let status = false;
    if (event === 0 || event === 1) {
      status = true;
    }
    if (this.showStatus != status) {
      this.initFormGroup(event);
    }
  }

  createChooseAnswerList() {
    this.chooseAnswer = [];
    const self = this;
    this.formData.options.forEach(function (value, i) {
      self.chooseAnswer.push({label : self.answerList[i], value: self.answerList[i]});
    })
  }
}
